package com.yangjun.controller.usermanage;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;
import com.yangjun.dao.impl.usermanage.UserManageDaoImpl;
import com.yangjun.dao.mybatis.mapper.usermanage.UserManageMapper;
import com.yangjun.entity.usermanage.LogEntity;
import com.yangjun.entity.usermanage.MenuEntity;
import com.yangjun.entity.usermanage.UsersEntity;
import com.yangjun.utils.AjaxJson;

@Controller
@RequestMapping("/user")
public class UserManageController {
	
	@Autowired
	private UserManageMapper mapper;
	
	@Autowired
	UserManageDaoImpl dao;
	
	/**
	 * #########################菜单管理#################################
	 */
	
	/**
	 * http://192.168.7.32:8080/user/getMenuUsers?menuid=100
	 * 当前菜单有权限的用户
	 * @param response
	 * @param menuid
	 * @return
	 */
	 @RequestMapping("/getMenuUsers")
	 @ResponseBody
	 public AjaxJson getMenuUsers(HttpServletResponse response,
			 @RequestParam(value = "menuid",required = true)String menuid){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 List<UsersEntity> menuUsers = mapper.getMenuUsers(menuid);
		 Map<String, Object> attributes = Maps.newHashMap();
		 attributes.put("menuUsers", menuUsers);
		 j.setAttributes(attributes);
		 return j;
	 }
	 
	 
	 /**
	  * 192.168.7.32:8080/user/getNoCurrentMenuUsers?menuid=120&name=
	  * 当前菜单无权限的用户
	  * @param response
	  * @param menuid
	  * @param username
	  * @param realname
	  * @return
	  */
	 @RequestMapping("/getNoCurrentMenuUsers")
	 @ResponseBody
	 public AjaxJson getNoCurrentMenuUsers(HttpServletResponse response,
			 @RequestParam(value = "menuid",required = true)String menuid,
			 @RequestParam(value = "name",required = false)String name){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 List<UsersEntity> noCurrentMenuUsers = mapper.getNoCurrentMenuUsers(menuid,name);
		 Map<String, Object> attributes = Maps.newHashMap();
		 attributes.put("noCurrentMenuUsers", noCurrentMenuUsers);
		 j.setAttributes(attributes);
		 return j;
	 }
	 
	 /**
	  * 192.168.7.32:8080/user/updateUserMenuStatus?userid=1&menuid=100&value=
	  * 修改用户菜单的状态
	  * @param response
	  * @param userid
	  * @param menuid
	  * @param value
	  * @return
	  */
	 @RequestMapping("/updateUserMenuStatus")
	 @ResponseBody
	 public AjaxJson updateUserMenuStatus(HttpServletResponse response,
			 @RequestParam(value = "userid",required = true)String userid,
			 @RequestParam(value = "menuid",required = true)String menuid,
			 @RequestParam(value = "value",required = true)String value){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 boolean ok = dao.updateUserMenuStatus(Integer.parseInt(userid), Integer.parseInt(menuid), Integer.parseInt(value));
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 /**
	  * 192.168.7.32:8080/user/addUserMenu?userid=1&menuid=100
	  * 给用户添加菜单权限
	  * @param response
	  * @param userid
	  * @param menuid
	  * @return
	  */
	 @RequestMapping("/addUserMenu")
	 @ResponseBody
	 public AjaxJson addUserMenu(HttpServletResponse response,
			 @RequestParam(value = "userid",required = true)String userid,
			 @RequestParam(value = "menuid",required = false)String menuid){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 boolean ok = dao.addUserMenu(Integer.parseInt(userid), Integer.parseInt(menuid));
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 
	/**
	 * #########################权限管理#################################
	 */
	

	 /**
	  * 
	  * 192.168.7.32:8080/user/getAllUsers?name=
	  * 获取所有用户
	  * @param response
	  * @param name
	  * @return
	  */
	 @RequestMapping("/getAllUsers")
	 @ResponseBody
	 public AjaxJson getAllUsers(HttpServletResponse response,
			 @RequestParam(value = "name",required = false)String name){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 List<UsersEntity> noCurrentMenuUsers = mapper.getAllUsers(name);
		 Map<String, Object> attributes = Maps.newHashMap();
		 attributes.put("noCurrentMenuUsers", noCurrentMenuUsers);
		 j.setAttributes(attributes);
		 return j;
	 }
	 
	 /**
	  * 
	  * 192.168.7.32:8080/user/updateUserStatus?userid=&value=
	  * 修改用户使用状态
	  * @param response
	  * @param userid
	  * @param value
	  * @return
	  */
	 @RequestMapping("/updateUserStatus")
	 @ResponseBody
	 public AjaxJson updateUserStatus(HttpServletResponse response,
			 @RequestParam(value = "userid",required = true)String userid,
			 @RequestParam(value = "value",required = true)String value){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 boolean ok = dao.updateUserStatus(Integer.parseInt(userid),Integer.parseInt(value));
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 
	 /**
	  * 192.168.7.32:8080/user/updateUserPassword?userid=
	  * 重置用户密码
	  * @param response
	  * @param userid
	  * @param password
	  * @return
	  */
	 @RequestMapping("/updateUserPassword")
	 @ResponseBody
	 public AjaxJson updateUserPassword(HttpServletResponse response,
			 @RequestParam(value = "userid",required = true)String userid,
			 @RequestParam(value = "password",required = false)String password){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 boolean ok = dao.updateUserPassword(Integer.parseInt(userid),password);
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 
	 /**
	  * 192.168.7.32:8080/user/updatePassword?username=ceshi&oldpassword=123123&newpassword=123123
	  * 修改用户密码
	  * @param response
	  * @param username
	  * @param password
	  * @return
	  */
	 @RequestMapping("/updatePassword")
	 @ResponseBody
	 public AjaxJson updatePassword(HttpServletResponse response,
			 @RequestParam(value = "username",required = true)String username,
			 @RequestParam(value = "oldpassword",required = true)String oldpassword,
			 @RequestParam(value = "newpassword",required = true)String newpassword){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 boolean ok = dao.updatePassword(username,oldpassword,newpassword);
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("原始密码错误");
			 return j;
		 }
		 return j;
	 }
	 
	 /**
	  * 192.168.7.32:8080/user/updateUser?userid=&username=&realname
	  * 修改用户
	  * @param response
	  * @param userid
	  * @param username
	  * @param realname
	  * @return
	  */
	 @RequestMapping("/updateUser")
	 @ResponseBody
	 public AjaxJson updateUser(HttpServletResponse response,
			 @RequestParam(value = "userid",required = true)String userid,
			 @RequestParam(value = "username",required = true)String username,
			 @RequestParam(value = "realname",required = true)String realname){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 
		 try {
			realname = java.net.URLDecoder.decode(realname,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		 boolean ok = dao.updateUser(Integer.parseInt(userid),username,realname);
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 
	 /**
	  * 192.168.7.32:8080/user/addUser?username=&realname=
	  * 新增用户
	  * @param response
	  * @param username
	  * @param realname
	  * @return
	  */
	 @RequestMapping("/addUser")
	 @ResponseBody
	 public AjaxJson addUser(HttpServletResponse response,
			 @RequestParam(value = "username",required = true)String username,
			 @RequestParam(value = "realname",required = true)String realname){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 
		 boolean isexsit = dao.isExistUser(username);
		 if(isexsit){
			 j.setSuccess(false);
			 j.setMsg("该用户已存在!");
		 }else{
			 boolean ok = dao.addUser(username,realname);
			 if(!ok){
				 j.setSuccess(false);
				 j.setMsg("操作失败");
				 return j;
			 }
		 }
		 
		 return j;
	 }
	 
	 
	 /**
	  * 192.168.7.32:8080/user/getUserMenu?userid=1
	  * 获取单个用户菜单
	  * @param response
	  * @param userid
	  * @return
	  */
	 @RequestMapping("/getUserMenu")
	 @ResponseBody
	 public AjaxJson getUserMenu(HttpServletResponse response,
			 @RequestParam(value = "userid",required = true) String userid){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 List<MenuEntity> allMenu = mapper.getAllMenu();
		 
		 List<MenuEntity> userMenuList = mapper.getUserMenu(userid);
		 for (MenuEntity menu : userMenuList) {
			 String mname = menu.getMenuname();
//			 Integer menuid = menu.getMenuid();
			 Integer parentid = menu.getParentid();
			 if(parentid!=null){
				 menu.setMenuname(digui(allMenu,mname,parentid));
			 }
		}
		 
		 Map<String, Object> attributes = Maps.newHashMap();
		 attributes.put("userMenu", userMenuList);
		 j.setAttributes(attributes);
		 return j;
	 }
	 
	 /**
	  * 递归菜单目录
	  * @param mname
	  * @param parentid
	  * @return
	  */
	 public String digui(List<MenuEntity> listMenu,String mname,Integer parentid){
		for (MenuEntity menu : listMenu) {
			if(parentid.intValue()==menu.getMenuid().intValue()){
				mname = menu.getMenuname()+"/"+mname;
//				System.err.println("mname----"+mname);
				if(menu.getParentid()!=null){
					return digui(listMenu,mname,menu.getParentid());
				}
				break;
			}
		}
		return mname;
	 }
	 
	 /**
	  * 
	  * 192.168.7.32:8080/user/addUserMenuList?userid=&menuidList=
	  * 权限管理--给单个用户添加权限列表
	  * @param response
	  * @param userid
	  * @param menuidList
	  * @return
	  */
	 @RequestMapping("/addUserMenuList")
	 @ResponseBody
	 public AjaxJson addUserMenuList(HttpServletResponse response,
			 @RequestParam(value = "userid",required = true)String userid,
			 @RequestParam(value = "menuidList",required = true)String menuidList){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 
		 AjaxJson j = new AjaxJson();
		 if(StringUtils.isBlank(menuidList)){
			 return j;
		 }
		 try {
			String[] menuidSz = menuidList.trim().split(",");
			 for(int i=0;i<menuidSz.length;i++){
				 dao.addUserMenu(Integer.parseInt(userid), Integer.parseInt(menuidSz[i]));
			 }
		} catch (Exception e) {
			 j.setSuccess(false);
			 j.setMsg("操作失败");
			 e.printStackTrace();
		}
		 return j;
	 }
	 
	 
	 /**
	  * 
	  * 
	  * http://192.168.7.32:8080/user/addUserVisitLog?username=ceshi&menuname=&url=
	  * @param response
	  * @param username
	  * @return
	  */
	 @RequestMapping("/addUserVisitLog")
	 @ResponseBody
	 public AjaxJson addUserVisitLog(HttpServletResponse response,
			 HttpServletRequest request,
			 @RequestParam(value = "username", required = true) String username,
			 @RequestParam(value = "url", required = true) String url){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 Map<String, Object> attributes = Maps.newHashMap();
		 String ip = getIp(request);
//		 dao.deleteUserLog(username,ip);
		 dao.addUserLog(username,ip,url);
		 j.setAttributes(attributes);
		 return j;
	 }
	 

	 /**
	  * http://192.168.7.32:8080/user/addUserOnclickVisitLog?username=ceshi&clicktype=self_download&url=xxx
	  * @param response
	  * @param request
	  * @param username 用户名
	  * @param clicktype 点击类型
	  * @param url 访问接口
	  * @return
	  */
	 @RequestMapping("/addUserOnclickVisitLog")
	 @ResponseBody
	 public AjaxJson addUserOnclickVisitLog(HttpServletResponse response,
			 HttpServletRequest request,
			 @RequestParam(value = "username", required = true) String username,
			 @RequestParam(value = "clicktype", required = true) String clicktype,
			 @RequestParam(value = "url", required = true) String url){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 Map<String, Object> attributes = Maps.newHashMap();
		 String ip = getIp(request);
		 dao.addOnclickUserLog(username,clicktype,ip,url);
		 j.setAttributes(attributes);
		 return j;
	 }
	 
	 /**
	  * 
	  * http://192.168.7.32:8080/user/getAllUserLog
	  * 获取用户日志
	  * @param response
	  * @param name
	  * @return
	  */
	 @RequestMapping("/getAllUserLog")
	 @ResponseBody
	 public AjaxJson getAllUserLog(HttpServletResponse response,
		 @RequestParam(value = "name", required = false) String name){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 List<LogEntity> logList = mapper.getAllUserLog(name);
		 Map<String, Object> attributes = Maps.newHashMap();
		 attributes.put("logList", logList);
		 j.setAttributes(attributes);
		 return j;
	 }
	 
	 /**
	  * http://192.168.7.32:8080/user/getAllUserLogDetail?username=&ip=
	  * @param response
	  * @param username
	  * @param ip
	  * @return
	  */
	 @RequestMapping("/getAllUserLogDetail")
	 @ResponseBody
	 public AjaxJson getAllUserLogDetail(HttpServletResponse response,
			 @RequestParam(value = "username", required = true) String username,
			 @RequestParam(value = "ip", required = false) String ip
			 ){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 List<LogEntity> logDetailList = mapper.getAllUserLogDetail(username,ip);
		 Map<String, Object> attributes = Maps.newHashMap();
		 attributes.put("logDetailList", logDetailList);
		 j.setAttributes(attributes);
		 return j;
	 }
	 
	
	 public static String getIp(HttpServletRequest request) {
         String ip = request.getHeader("X-Forwarded-For");
         if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
             //多次反向代理后会有多个ip值，第一个ip才是真实ip
             int index = ip.indexOf(",");
             if(index != -1){
                 return ip.substring(0,index);
             }else{
                 return ip;
             }
         }
         ip = request.getHeader("X-Real-IP");
         if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
             return ip;
         }
         return request.getRemoteAddr();
     }
}
